package com.qcby.util;

import com.qcby.common.ExamDetail.ExamSubmitRequest;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class DeepSeekUtils {
    // 注意：API_KEY 和 API_URL 需根据 DeepSeek 官方最新文档验证正确性
    private static final String API_KEY = "Bearer sk-56169048534f4fb5aab3bd54a1c56a54";
    private static final String API_URL = "https://api.deepseek.com/chat/completions";

    // 全局复用 OkHttpClient（避免重复创建，提升性能）
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)   // 连接超时：30秒
            .readTimeout(60, TimeUnit.SECONDS)      // 读取超时：60秒（AI接口响应可能较慢）
            .writeTimeout(30, TimeUnit.SECONDS)     // 写入超时：30秒
            .build();

    /**
     * 调用DeepSeek AI接口获取响应
     * @param question 用户提问内容
     * @return AI返回的回答内容，失败时返回null
     * @throws IOException 当网络请求失败时抛出
     */
    public String askAi(String question) throws IOException {
        // 构建请求JSON（使用try-with-resources或手动转义，避免特殊字符导致的JSON格式错误）
        String jsonBody = String.format("{"
                + "  \"model\": \"deepseek-chat\","
                + "  \"messages\": ["
                + "    {\"role\": \"user\", \"content\": \"%s\"}"
                + "  ],"
                + "  \"temperature\": 0.7,"
                + "  \"top_p\": 0.8"
                + "}", escapeJson(question));  // 转义特殊字符，避免破坏JSON结构

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                jsonBody
        );

        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", API_KEY)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("AI接口请求失败: 状态码=" + response.code() + "，信息=" + response.message());
            }
            System.out.println("jsonBody"+jsonBody);
            // 仅读取一次响应体，避免流关闭导致的问题
            String responseJson = response.body().string();
            System.out.println("AI接口响应结果:\n" + responseJson);

            // 解析JSON响应
            return parseAiResponse(responseJson);
        }
    }

    /**
     * 解析AI接口返回的JSON响应
     * @param responseJson 接口返回的原始JSON字符串
     * @return 提取的回答内容，解析失败返回null
     */
    private String parseAiResponse(String responseJson) {
        try {
            JSONObject jsonObject = new JSONObject(responseJson);
            JSONArray choices = jsonObject.getJSONArray("choices");
            if (choices.length() == 0) {
                System.out.println("AI响应中未包含有效回答");
                return null;
            }
            JSONObject choice = choices.getJSONObject(0);
            JSONObject messageObj = choice.getJSONObject("message");
            return messageObj.getString("content");
        } catch (JSONException e) {
            System.err.println("解析AI响应JSON失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 转义JSON中的特殊字符（避免双引号、换行等破坏JSON结构）
     * @param input 原始字符串
     * @return 转义后的字符串
     */
    private String escapeJson(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    /**
     * 将题目列表转换为适合AI处理的文本格式
     */
    public String convertQuestionsToText(List<ExamSubmitRequest.QuestionDTO> questions) {
        StringBuilder sb = new StringBuilder();
        for (ExamSubmitRequest.QuestionDTO question : questions) {
            sb.append("题目ID: ").append(question.getQuestion_id()).append("\n");
            sb.append("题型: ").append(question.getType()).append("\n");
            sb.append("题目内容: ").append(question.getQuestion()).append("\n");

            // 如果有选项，添加选项信息
            if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                sb.append("选项: \n");
                for (String option : question.getOptions()) {
                    sb.append("- ").append(option).append("\n");
                }
            }

            sb.append("学生答案: ").append(question.getUser_answer()).append("\n");
            sb.append("-------------------------\n");
        }
        return sb.toString();
    }
}